import 'dart:convert';
import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:path_provider/path_provider.dart';

///json的解析工具
class CommonJson {
  ///获取某类型的列表
  static Future<List<T>> getList<T>(dynamic json, T Function(dynamic json) func, {required String keyName}) async {
    List? list;

    if (json is List) {
      list = json;
    } else {
      list = json[keyName];
    }

    if (list == null) return Future.value(<T>[]);
    List<T> result = list.map((e) => func(e)).toList();
    return result;
  }

  static Future<String> _getCachePath(String path) async {
    if (path.startsWith('/')) path = path.substring(1);
    var cacheDir = await getTemporaryDirectory();
    return '${cacheDir.path}/$path';
  }

  static void _downloadJson(
    String url,
    String path,
    ValueChanged<dynamic> complete, {
    VoidCallback? error,
  }) async {
    var dio = Dio();
    try {
      String cachePath = await _getCachePath(path);
      var file = File(cachePath);

      // if (await file.exists()) {
      //   var jsonString = await file.readAsString();
      //   complete(jsonDecode(jsonString));
      // }

      await dio.download(url, cachePath);

      if (await file.exists()) {
        var jsonString = await file.readAsString();
        complete(jsonDecode(jsonString));
      } else {
        complete({});
      }
    } catch (e) {
      error?.call();
    }
  }

  ///所有项目数据
  static void getProjectData(ValueChanged<dynamic> complete, {VoidCallback? error}) {
    _downloadJson('https://lami.chwxkj.top/pdata/items.json', 'json/items.json', complete, error: error);
  }

  ///所有店铺数据
  static void getShopsData(ValueChanged<dynamic> complete, {VoidCallback? error}) {
    _downloadJson('https://lami.chwxkj.top/pdata/shops.json', 'json/shops.json', complete, error: error);
  }

  ///所有技师数据
  static void getTechnicianData(ValueChanged<dynamic> complete, {VoidCallback? error}) {
    _downloadJson('https://lami.chwxkj.top/pdata/users.json', 'json/users.json', complete, error: error);
  }

  ///首页数据   推荐技师、banner、推荐项目
  static void getHomeData(ValueChanged<dynamic> complete, {VoidCallback? error}) {
    _downloadJson('https://lami.chwxkj.top/pdata/home.json', 'json/home.json', complete, error: error);
  }
}
